﻿/*
 AIRDROPPING.SQF
 ===============
 © Pumpkin

 version 2.2
 - normalisation de la méthode de détection client
 - ajout du paramètre de disparition des marqueurs

 Script gérant l'apparition de l'avion et du pilote ainsi que le trajet vers la position de parachutage; lancé par MarqueDropPos.sqf mais peut aussi être lancé en solo

 Paramètres :
 ------------
 nul = [position, [materiel1,materiel2,...], attente (,type d'avion ,temporisation)] execVM "AirSupply\AirDropping.sqf"

 1. position du dropping : une coordonnee quelconque
 2. tableau du materiel largé : 2 manières de le remplir : soit avec le nom des objets -CRÉER AU SOL-, soit avec une chaine vide comme 1er élément
                                   suivi de la classe d'objet à générer; la 1ère façon permet de modifier l'objet (ajout de munitions,...) et la
                                   gestion de l'objet grace à sa variable nom; la 2ème façon permet la génération de matériel à volonté.
 3. attente : délai d'attente avant la venu de l'avion ravitailleur sur site de parachutage
 4. et 5. type d'avion : (optionnel) "MV22" par défaut (pour ARMA2; avion plus maniable que le C130J)
          temporisation : delai avant disparition du marqueur, marqueur permanent par défaut

*/


Server_Detected = call compile preprocessFile "scripts\common.sqf";
if (!X_Client) exitwith {};

if (player != leader group player) exitwith {hint "Only leaders can call in AirDrops"};
Diag_log Format["Calling the AirDrop with %1 parameters to %2", count _this, _this select 0];

private ["_extfunction","_arrayObject","_allowDamage","_obj","_arguments","_iArgs","_target","_i","_dir","_cnt","_dy","_dx","_ang","_pilote","_grppilot","_transport","_alti","_dist","_eloignmt","_param","_tempo","_planetype","_attente","_supplies","_droppos"];

_droppos = _this select 0;
If (_droppos select 2 < 0) then {
	_droppos = [(_droppos select 0),(_droppos select 1),0];
};
_supplies = _this select 1;
_attente = _this select 2;
_planetype = "MV22";
_tempo = -1;

if (count _this > 3) then {
	_param = _this select 3;
	if (typename _param == "STRING") then { _planetype = _param };
	if (typename _param == "SCALAR") then { _tempo = _param };
};

if (count _this > 4) then {
	_param = _this select 4;
	if (typename _param == "STRING") then { _planetype = _param };
	if (typename _param == "SCALAR") then { _tempo = _param };
};

if (PUMPKIN_ravitail) exitwith {hint "Air Supply already in progress... Please try again later"};
PUMPKIN_ravitail = true;
publicvariable "PUMPKIN_ravitail";

// distance d'apparition de l'avion
_eloignmt = 3000;
// distance de largage
_dist = 50;
// altitude de vol;
_alti = 250;

// gestion du marqueur "Largage"
createMarker ["PUMPKIN_AirDrop", [0,0]];
"PUMPKIN_AirDrop" setMarkerType "Pickup";
"PUMPKIN_AirDrop" setMarkerColor "ColorGreen";
"PUMPKIN_AirDrop" setMarkerSize [1,1];
"PUMPKIN_AirDrop" setMarkerText "Largage";
"PUMPKIN_AirDrop" setMarkerPos _droppos;


// génération de l'avion et du pilote
_transport = createVehicle [_planetype, [0,0], [], 0, "FLY"];
waituntil{ _planetype == typeOf _transport };
_transport allowdamage false;
_allowDamage = False;
//player sidechat format ["plane %1",_transport];

_grppilot = creategroup WEST;
["USMC_Soldier_Pilot", _grppilot, [0,0,0], 0, "SupplyPilot1=this"] call XfCreateUnit;
//_pilote = "USMC_Soldier_Pilot" createUnit [[0,0,0], _grppilot, "SupplyPilot1=this"];
waituntil{ SupplyPilot1 isKindOf "Man" };

SupplyPilot1 moveinDriver _transport;
SupplyPilot1 allowdamage true;
SupplyPilot1 setcaptive true;

_transport flyInHeight _alti;

sleep _attente;

// Choix au hasard de la position de laquelle l'avion arrive
_ang = random 360;
_dx = (sin _ang) * _eloignmt;
_dy = (cos _ang) * _eloignmt;
_transport setpos [(_droppos select 0)+_dx,(_droppos select 1)+_dy, getpos _transport select 2];

SupplyPilot1 move _droppos;
SupplyPilot1 sidechat format ["Air Support to team %1 ! On the way!",group player];

// Test de distance avec ordre de waypoint toutes les 5s
_cnt = 0;
while { (SupplyPilot1 distance _droppos > (_dist + _alti)) AND (alive _transport)} do {
	if (_cnt > 10) then {
		_cnt = 0;
		SupplyPilot1 move _droppos;
	};
	If ( !_allowDamage And (SupplyPilot1 distance _droppos < 1500)) then {
		_allowDamage = True;
		_transport allowDamage true;
	};
	_cnt = _cnt + 1;
	sleep 0.5;
};

If (alive _transport) then {

	diag_log Format["Drop Pos Reached"];

	// Pilote a bonne distance, LARGAGE !
	for [{_i = 0},{_i < count _supplies},{_i = _i + 1}] do {

		_dir = direction _transport;
		_target = [(getpos _transport select 0)-(15 * sin _dir),(getpos _transport select 1)-(15 * sin _dir),(getpos _transport select 2) - 10];
		//_target = [(getpos _transport select 0),(getpos _transport select 1),getpos _transport select 2];

		// Mode 1 : parachutage d'objets existants
		//if (format ["%1",_supplies select 0] != "") then {
		if (typename (_supplies select _i) == "OBJECT") then {
			diag_log Format["AirDrop moving %1 (%2)", typeof (_supplies select _i),vehicleVarName (_supplies select _i)];
			(_supplies select _i) allowDammage false;
			[_supplies select _i, _target, _tempo] execVM "scripts\AirSupply\ASDropSupply2.sqf";
		};
		// Mode 2 : création des objets à l'aide du type
		//if ((format ["%1",_supplies select 0] == "") and (_i > 0)) then {
		if (typename (_supplies select _i) == "STRING") then {
			diag_log Format["AirDrop instantiating %1",(_supplies select _i)];
			_obj = (_supplies select _i) createVehicle [0,0,0];
			_obj allowDammage false;
			[_obj, _target, _tempo] execVM "scripts\AirSupply\ASDropSupply2.sqf";
		};

		// Mode 2 : création des objets à l'aide du type + ligne d'initialisation
		//if ((format ["%1",_supplies select 0] == "") and (_i > 0)) then {
		if (typename (_supplies select _i) == "ARRAY") then {
			_arrayObject = _supplies select _i;
			_obj = (_arrayObject select 0) createVehicle [0,0,0];
			_extfunction = "";
			If (count _arrayObject > 1) then {
				_extfunction = (_arrayObject select 1);
				_arguments = [_obj];
				If (count _arrayObject > 2) then{
					for [{_iArgs = 2},{_iArgs < count _arrayObject},{_iArgs = _iArgs + 1}] do {
						_arguments set [(_iArgs - 1) , (_arrayObject select _iArgs)];
					};
				};
				nul = _arguments spawn (compile preprocessFile  _extfunction);
				diag_log Format["AirDrop instantiating %1 and executing: '%2 spawn %3'",(_arrayObject select 0), _arguments, _extfunction];
			} else {
				diag_log Format["AirDrop instantiating %1",(_arrayObject select 0)];
			};
			_obj allowDammage false;
			[_obj, _target, _tempo] execVM "scripts\AirSupply\ASDropSupply2.sqf";
		};

		sleep 0.1;
	};
} else {
	SupplyPilot1 sidechat Format["Air Support has been destroyed!"];
	X_AirSupplyIsAvailable = false;
	publicVariable "X_AirSupplyIsAvailable";
};

sleep 1;

If (alive _transport) then {
	// Largage terminé, éloignement et disparition
	_dir = getdir _transport;
	_newwp = [(_droppos select 0)+(sin _dir*(_eloignmt)),(_droppos select 1)+(cos _dir*(_eloignmt)),0];
	SupplyPilot1 move _newwp;

	_transport flyInHeight 2000;
};

// ... Et si un bug se produit, forcer la disparition de l'avion avec un timeout
_starttime=daytime;
//player groupchat format ["t1 = %1",_starttime];
_timelimit = 60;
_cnt = 0;
while {((SupplyPilot1 distance _droppos) < _eloignmt) AND (alive _transport)} do
{
	_cnt = _cnt + 1;
	if (_cnt > 4) then {
		_cnt = 0;
		SupplyPilot1 move _newwp;
	};
	If ( _allowDamage And (SupplyPilot1 distance _droppos > 1500)) then {
		_allowDamage = False;
		_transport allowDamage False;
	};
	_timeout = (daytime - _starttime) * 3600;
	if (_timeout > _timelimit) exitWith {clickok=false};
	sleep 0.5;
};

deletevehicle SupplyPilot1;
sleep 1;
deletevehicle _transport;

If (!(alive _transport) And X_AirSupplyIsAvailable) then {
	SupplyPilot1 sidechat Format["Air Support has been destroyed!"];
	X_AirSupplyIsAvailable = false;
	publicVariable "X_AirSupplyIsAvailable";
};

PUMPKIN_ravitail = false;
publicvariable "PUMPKIN_ravitail";

deleteMarker "PUMPKIN_AirDrop";
